﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Web.UserControls;
using BSCMFF.Core.BusinessLayer;
using BSCMFF.Core.Exceptions.Database;
using System.Web.Security;

namespace BSCMFF.Web.Pages.Surveys
{
    public partial class FillSurvey : BSCMFF.Core.MultiLanguagePage
    {
        static string prevPage = String.Empty;

        //private static int questionsNumber;
        //private static List<int> questionsIDs;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //prevPage = Request.UrlReferrer == null ?  Request.UrlReferrer.ToString();
                if (Request.QueryString["Preview"] != null && Request.QueryString["Preview"] == "yes")
                {
                    prevPage = "Personalist/ManageSurveys.aspx";
                    string[] roles = Roles.GetRolesForUser();
                    if (roles[0] == "Personalist")
                    {
                        if (Request.QueryString["Survey_FormID"] != null)
                        {
                            int surID = Convert.ToInt32(Request.QueryString["Survey_FormID"]);
                            BSCEntities context = new BSCEntities();

                            Survey_Form selectedSurvey = (from sur in context.Survey_Form
                                                          where sur.ID == surID
                                                          select sur).SingleOrDefault();
                            if (selectedSurvey != null)
                            {
                                sd.Survey = selectedSurvey;
                                sd.DataBind();
                                LoadQuestions(surID);
                                PanelSurveyQuestions.Enabled = false;
                                RadButtonSend.Visible = false;
                            }
                        }
                    }
                    else
                    {
                        RadButtonSend.Visible = false;
                    }
                }
                else
                {
                    if (Request.QueryString["Survey_FormID"] != null)
                    {
                        int surID = Convert.ToInt32(Request.QueryString["Survey_FormID"]);
                        int loggedUserID = 0;

                        if (Session["loggedUserID"] != null)
                        {
                            loggedUserID = (int)Session["loggedUserID"];
                        }

                        BSCEntities context = new BSCEntities();

                        Survey_Form selectedSurvey = (from surusers in context.Survey_User
                                                      where surusers.Survey_Form_FK == surID && surusers.User_FK == loggedUserID
                                                            && surusers.Filled == false
                                                      select surusers.Survey_Form).SingleOrDefault();

                        if (selectedSurvey != null)
                        {
                            sd.Survey = selectedSurvey;
                            sd.DataBind();

                            //questionsNumber = 0;
                            //questionsIDs = new List<int>();
                            LoadQuestions(surID);

                            //zabranit opakovanemu vyhodnoteniu
                            /*if (selectedSurvey.Survey_User.FirstOrDefault().Filled == true)
                            {
                                PanelSurveyQuestions.Enabled = false;
                                RadButtonSend.Visible = false;
                            }*/
                        }
                        else
                        {
                            RadButtonSend.Visible = false;
                        }
                    }
                    else
                    {
                        RadButtonSend.Visible = false;
                    }
                }
                
            }
            else
            {
                PersistQuestions();
            }
        }

        private void PersistQuestions()
        {
            int questionsNumber = Int32.Parse(HiddenFieldQuestionNumber.Value);
            for (int i = 0; i < questionsNumber; ++i)
            {
                SurveyQuestionControl sqc = LoadControl("~/UserControls/SurveyQuestionControl.ascx") as SurveyQuestionControl;
                sqc.ID = i.ToString();
                //Survey_Question sq = new Survey_Question();
                //sq.ID = questionsIDs[i];
                //sqc.SQ = sq;
                PanelSurveyQuestions.Controls.Add(sqc);
            }
        }

        private void LoadQuestions(int surID)
        {
            BSCEntities context = new BSCEntities();

            List<Survey_Question> questions = (from question in context.Survey_Question
                                               where question.Form_FK == surID
                                               select question).ToList();

            int questionsNumber = Int32.Parse(HiddenFieldQuestionNumber.Value);
            foreach (Survey_Question sq in questions)
            {

                SurveyQuestionControl sqc = LoadControl("~/UserControls/SurveyQuestionControl.ascx") as SurveyQuestionControl;
                sqc.ID = (questionsNumber++).ToString(); //sq.ID.ToString();
                sqc.SQ = sq;

                PanelSurveyQuestions.Controls.Add(sqc);
               // ++questionsNumber;
           //     questionsIDs.Add(sq.ID);
                //Label l = new Label();
                //l.ID = "LabelQuestion" + sq.ID;
                //l.Text = sq.Question;

            }

            HiddenFieldQuestionNumber.Value = questionsNumber.ToString();
        }

        protected void RadButtonSend_Click(object sender, EventArgs e)
        {
            BSCEntities context = new BSCEntities();


            //string login = User.Identity.Name;
            //UserManager um = new UserManager();
            //User currentUser = um.GetUserByLogin(login);
            int surID = Convert.ToInt32(Request.QueryString["Survey_FormID"]);
            int loggedUserID = (int)Session["loggedUserID"];

            foreach (Control c in PanelSurveyQuestions.Controls)
            {
                if (c.GetType().BaseType.Name == "SurveyQuestionControl")
                {
                    SurveyQuestionControl sqc = (SurveyQuestionControl)c;
                    
                    Survey_Results sr = new Survey_Results();
                    sr.User_FK = loggedUserID;
                    int? answerID = sqc.GetSelectedAnswerID();
                    if (answerID != null)
                    {
                        sr.Answer_FK = (int)answerID;

                        context.AddToSurvey_Results(sr);
                    }
                }
            }

            Survey_User su = (from surusers in context.Survey_User
                             where surusers.Survey_Form_FK == surID && surusers.User_FK == loggedUserID
                             select surusers).SingleOrDefault();
            su.Filled = true;
            su.DateFilled = DateTime.Today;

            try
            {
                context.SaveChanges();
                Response.Redirect("../UserPages/EmployeeInfo.aspx?EmployeeID=" + loggedUserID);
            }
            catch
            {
                throw new InconsistentDatabaseException("Couldn't save survey results");
            }
        }

        protected void RadButtonBack_Click(object sender, EventArgs e)
        {
            int loggedUserID = (int)Session["loggedUserID"];
            //Response.Redirect("../Administration/EmployeeInfo.aspx?EmployeeID=" + loggedUserID);

            Response.Redirect(prevPage);
        }
    }
}